package com.zhuiyun.pm.client.login.service.serviceImp;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.zhuiyun.pm.client.login.mapper.UserLoginDao;
import com.zhuiyun.pm.client.login.entity.ClientUser;
import com.zhuiyun.pm.client.login.service.UserLoginService;
import com.zhuiyun.pm.client.login.utils.TokenUtils;
import com.zhuiyun.pm.config.CommonResult;
import com.zhuiyun.pm.utils.MailUtils;
import com.zhuiyun.pm.utils.Md5Util;
import com.zhuiyun.pm.utils.RedisUtil;
import com.zhuiyun.pm.utils.ShortMessageUtils;
import com.zhuiyun.pm.utils.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;

import java.util.Random;
import java.util.UUID;
import java.util.List;

/**
 * @author syc
 * @date 2023/3/13 19:28
 */
@Service
public class UserLoginServiceImp implements UserLoginService {
    @Autowired
    UserLoginDao clientUserDao;
    @Autowired
    RedisUtil redisUtil;
    @Autowired
    UploadFileUtils uploadFiles;



    /**
     * 查询手机是否有该用户
     * 有个话存在redis中
     * @param clientUser
     * @return
     */
    @Override
    public CommonResult queryByPhone(ClientUser clientUser) {
        clientUser.setDelFlag(0);
        final Object o1 = redisUtil.get(clientUser.getUserPhone());
//        List<ClientUser> o = (List<ClientUser>) redisUtil.get(clientUser.getUserPhone());
        if(o1!=null){
            return CommonResult.ok("手机存在");
        }else{
            final List<ClientUser> select = clientUserDao.select(clientUser);
            if(!select.isEmpty()){
                redisUtil.set(clientUser.getUserPhone(),select.get(0),1000);
                return CommonResult.ok("登录成功");
            }else{
                return CommonResult.error("该手机号未注册");
            }
        }
    }
    /**
    * @Author sgo
    * @Description 登录判断密码账户
    * @Date 2023/3/14 14:02
    * @Return com.zhuiyun.pm.config.CommonResult
    * @param clientUser
    */
    @Override
    public CommonResult loginByPassWord(ClientUser clientUser) {
        final  ClientUser clientUsers = (ClientUser) redisUtil.get(clientUser.getUserPhone());
        if(clientUsers!=null){
            if(Md5Util.getMd5DigestAsHex(clientUser.getUserPassword()).equals(clientUsers.getUserPassword())){
                if(clientUsers.getUserStatus()==0){
//                    JWt
                    TokenUtils tokenUtil=new TokenUtils();
                    String uid = clientUsers.getUserPhone();
                    System.out.println("uid:" + uid);
                    String result = tokenUtil.createToken(uid);
                    System.out.println("生成的token：" + result);
                    String uidOut = tokenUtil.checkToken(result);
                    System.out.println("解密token后的uid：" + uidOut);
//                    DecodedJWT decodedJWT = tokenUtil.decode(result);
//                    System.out.println("Header:" + decodedJWT.getHeader());
//                    System.out.println("Payload:" + decodedJWT.getPayload());
//                    System.out.println("Signature:" + decodedJWT.getSignature());
//                    System.out.println("Token:" + decodedJWT.getToken());
//                redisUtil.del(clientUser.getUserPhone());
                    redisUtil.set(result,clientUsers,5000);
                    return CommonResult.ok(result);
                }else if(clientUsers.getUserStatus()==1){
                    return CommonResult.error("账号已经被封禁");
                }else{
                    return CommonResult.error("风控");
                }
            }else {
                return CommonResult.error("密码错误");
            }
        }else{
            return CommonResult.error("密码错误");
        }

    }
    /**
    * @Author sgo
    * @Description 发送手机验证码
    * @Date 2023/3/14 18:50
    * @Return com.zhuiyun.pm.config.CommonResult
    * @param phone
    */
    @Override
    public CommonResult sendloginByPhone(String phone) {
        ShortMessageUtils.sendPhoeRedis(phone,"a");
        return CommonResult.ok("已经发送");
    }
    /**
    * @Author sgo
    * @Description 验证码登录
    * @Date 2023/3/14 19:48
    * @Return com.zhuiyun.pm.config.CommonResult
    * @param
    * @param code
    */
    @Override
    public CommonResult loginByPhone(String userEmail, String code) {

        final String code1 =(String)  redisUtil.get(userEmail);
        ClientUser clientUser=new ClientUser();
        clientUser.setUserEmail(userEmail);
        clientUser.setDelFlag(0);
        List<ClientUser> select = clientUserDao.select(clientUser);
//        final List<ClientUser> list = (List<ClientUser>) redisUtil.get(phone);
        if(code.equals(code1)){
            TokenUtils tokenUtil=new TokenUtils();
            String uid = select.get(0).getUserPhone();
            System.out.println("uid:" + uid);
            String result = tokenUtil.createToken(uid);
            System.out.println("生成的token：" + result);
            String uidOut = tokenUtil.checkToken(result);
            System.out.println("解密token后的uid：" + uidOut);
                redisUtil.set(result,select.get(0),5000);
                return CommonResult.ok(result);
        }else{
            return  CommonResult.error("验证码过期");
        }
    }
    /**
    * @Author sgo
    * @Description 注册
    * @Date 2023/3/16 9:50
    * @Return com.zhuiyun.pm.config.CommonResult
    * @param clientUser
    * @param code
    */
    @Override
    public CommonResult register(ClientUser clientUser,String code) {
//        判断手机号有没有注册
        ClientUser clientUser1=new ClientUser();
        clientUser1.setUserPhone(clientUser.getUserPhone());
        clientUser1.setDelFlag(0);
        List<ClientUser> select = clientUserDao.select(clientUser1);
        if(select.isEmpty()){
            String rcode = (String) redisUtil.get(clientUser.getUserEmail());
            if(!rcode.isEmpty()){
                if(rcode.equals(code)){
                    int i = clientUserDao.insertSelective(clientUser);
                    if(i>0){
                        return CommonResult.ok("添加成功");
                    }else{
                        return CommonResult.ok("添加失败");
                    }
                }else {
                    return CommonResult.error("验证码输入不正确");
                }

            }else{
                return CommonResult.error("验证码已过期");
            }

        }else{
            return CommonResult.error("手机号已经注册");
        }
    }

    /**
     * @Author 赵笛
     * @Description TODO 根据token获取当前登录的用户
     * @Date 2023/3/19 18:55
     * @Return com.zhuiyun.pm.config.CommonResult
     * @param token
     */
    @Override
    public CommonResult getLoginUser(String token) {
        String token1 =token.substring(0,token.length()-1);
        ClientUser user = (ClientUser)redisUtil.get(token1);
//        JSONObject jsonObject = JSON.parseObject(user.toString());
//        ClientUser clientUser = JSON.toJavaObject(jsonObject,ClientUser.class);
        if(user!=null){
            return CommonResult.ok(user);
        }else {
            return CommonResult.error("暂未查询到登录用户");
        }
    }
    @Override
    public CommonResult AppLogin(ClientUser clientUser) {
        clientUser.setUserPassword(Md5Util.getMd5DigestAsHex(clientUser.getUserPassword()));
        ClientUser select = clientUserDao.selectOne(clientUser);
        if(select!=null){
            return CommonResult.ok(select);
        }else {
            return CommonResult.error("300");
        }
    }
    /**
    * @Author f
    * @Description  发送邮箱
    * @Date 2023/3/21 20:22
    * @Return com.zhuiyun.pm.config.CommonResult
    * @param userEmail
    */
    @Override
    public CommonResult sendMail(String userEmail,String type) {
//        登录
        if(type.equals("1")){
            ClientUser clientUser=new ClientUser();
            clientUser.setUserEmail(userEmail);
            clientUser.setDelFlag(0);
            ClientUser clientUser1 = null;
            clientUser1 = clientUserDao.selectOne(clientUser);
            if(clientUser1!=null){
                Random random = new Random();
                String result = "";
                for ( int i = 0; i < 6; i++) {
                    result += random.nextInt(10);
                }
                System.out.println(result);
                MailUtils.sendMail(userEmail,"附近的人:","您好，我是小丽，自己一个人住，下班了想找个人聊聊天。输入验证码:"+result);
                redisUtil.set(userEmail,result,500);
                return CommonResult.ok("发送成功");
            }else{
                return CommonResult.error("改邮箱还未注册");
            }
        }else{
            ClientUser clientUser=new ClientUser();
            clientUser.setUserEmail(userEmail);
            clientUser.setDelFlag(0);
            ClientUser clientUser1 = null;
            clientUser1 = clientUserDao.selectOne(clientUser);
            if(clientUser1==null){
                Random random = new Random();
                String result = "";
                for ( int i = 0; i < 6; i++) {
                    result += random.nextInt(10);
                }
                System.out.println(result);
                MailUtils.sendMail(userEmail,"验证码:","您的验证码是:"+result);
                redisUtil.set(userEmail,result,500);
                return CommonResult.ok("发送成功");
            }else{
                return CommonResult.error("该邮箱已经注册过");
            }
        }


    }

    /**
     * 用户修改信息回显
     * @author 温
     * @date 2023/3/21 15:14
     * @parameter [id]
     * @return com.zhuiyun.pm.client.login.entity.ClientUser
     */
    @Override
    public ClientUser clientUserId(int id) {
        ClientUser clientUser = clientUserDao.selectByPrimaryKey(id);
        return clientUser;
    }


    /**
     * 修改用户个人信息
     * @author 温
     * @date 2023/3/21 16:01
     * @parameter [file, clientUser]
     * @return int
     */
    @Override
    public CommonResult clientUserUpdate(MultipartFile file, ClientUser clientUser,String token) {
        if (StringUtils.isEmpty(clientUser.getUserPhone())) {// 如果 userPhone 是空的，则抛出异常
            throw new IllegalArgumentException("userPhone should not be null or empty.");
        }
        if (StringUtils.isEmpty(token)) {// 如果 token 是空的，则抛出异常
            throw new IllegalArgumentException("token should not be null or empty.");
        }
        int i=0;
        if(file!=null){
            String s = uploadFiles.uploadFile(file);
            if(!StringUtils.isEmpty(s)){
                clientUser.setImageId(s);//不为空，则将其赋值给 clientUser 对象的 imageId 属性。
            }
        }
        System.out.println("clientUser::"+clientUser);// 打印
        i=clientUserDao.updateByPrimaryKeySelective(clientUser);
        if(i>0){
            redisUtil.del(clientUser.getUserPhone());
            redisUtil.del(token);
            final ClientUser clientUser1 = clientUserDao.selectOne(clientUser); //根据 clientUser 对象的属性查询数据库中对应的记录，并将返回的对象赋值给 clientUser1 变量。
            if(clientUser1!=null){//如果查询结果不为空，则创建一个 TokenUtils 对象， 方法根据用户的手机号生成 token。
                TokenUtils tokenUtil=new TokenUtils();
                String uid = clientUser1.getUserPhone(); // 根据手机号生成token
//                System.out.println("uid:" + uid);
                String result = tokenUtil.createToken(uid);//赋值给result
//                System.out.println("生成的token：" + result);
                String uidOut = tokenUtil.checkToken(result);//方法解密生成的 token 值，并将解密后的结果赋值给字符串变量 uidOut。
//                System.out.println("解密token后的uid：" + uidOut);
                redisUtil.set(result,clientUser1,1000); // 存入redis中
                return CommonResult.ok(result);
            }else{
                return CommonResult.error("修改失败");
            }
        }else{
            return CommonResult.error("修改失败");
        }



    }

    @Override
    public CommonResult revisePassWord(ClientUser clientUser,String token) {
        final String md5DigestAsHex = Md5Util.getMd5DigestAsHex(clientUser.getUserPassword());
        clientUser.setUserPassword(md5DigestAsHex);
        int a=clientUserDao.updateByPrimaryKeySelective(clientUser);
        redisUtil.del(clientUser.getUserPhone());
        if(a>0) {
            redisUtil.del(clientUser.getUserPhone());
            redisUtil.del(token);
            final ClientUser clientUser1 = clientUserDao.selectOne(clientUser);
            if (clientUser1 != null) {
                TokenUtils tokenUtil = new TokenUtils();
                String uid = clientUser1.getUserPhone();
//                System.out.println("uid:" + uid);
                String result = tokenUtil.createToken(uid);
//                System.out.println("生成的token：" + result);
                String uidOut = tokenUtil.checkToken(result);
//                System.out.println("解密token后的uid：" + uidOut);
                redisUtil.set(result, clientUser1, 1000);
                return CommonResult.ok(result);
            } else {
                return CommonResult.error("修改失败");
            }
        }else{
            return CommonResult.ok("修改失败");
        }

    }

    /**
     * 用户模糊查
     * @author 温
     * @date 2023/4/4 16:35
     * @parameter [userName]
     * @return java.util.List<com.zhuiyun.pm.client.login.entity.ClientUser>
     */
    @Override
    public List<ClientUser> userMo(ClientUser clientUser) {
        List<ClientUser> select = clientUserDao.select(clientUser);
        return select;
    }
}
